package com.deyuanyun.pic.settings.support.interceptor;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.deyuanyun.pic.common.dto.Result;
import com.deyuanyun.pic.common.util.web.RequestResponseContext;
import com.deyuanyun.pic.settings.controller.dto.UserSessionVO;
import com.deyuanyun.pic.settings.domain.prvlg.Menu;
import com.deyuanyun.pic.settings.support.cache.SessionCacheSupport;

/**
 * 为获取当前操作的request和response提供支持
 * spring use  ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
 * SqlUtil.clearLocalPage();
 */
public class RequestAndResponseInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = Logger.getLogger(RequestAndResponseInterceptor.class);
    //大url地址和菜单id的对应关系
    public static Map<String,String> urlIdMap=new HashMap<String,String>();
    static {

        urlIdMap.put("pipe","M0000000000000001000000000000000");
        urlIdMap.put("eqpt","M0000000000000002000000000000000");//移动设备
        urlIdMap.put("settings","M0000000000000003000000000000000");
        urlIdMap.put("userSelfInfo","M0000000000000003000000000000000");//个人设置
        urlIdMap.put("insp","M0000000000000008000000000000000");
        urlIdMap.put("pig","M0000000000000004000000000000000");
        urlIdMap.put("cleanTask","M0000000000000004000000000000000");
        urlIdMap.put("riskMgr","M0000000000000005000000000000000");
        urlIdMap.put("docmger","M0000000000000006000000000000000"); // 文档中心
        urlIdMap.put("ae","M0000000000000007000000000000000");//周边环境 10
        urlIdMap.put("pbf","M0000000000000008000000000000000");
        urlIdMap.put("corrctrl","M0000000000000009000000000000000");//腐蚀控制 9
        urlIdMap.put("integalz","M0000000000000010000000000000000");//完整性分析 10
        //
    }

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
        //统一增加一些页面变量
        request.setAttribute("nowDateTime_",new Date());
        request.setAttribute("jsfileVersion_","?vv=1");
        // spring mvc 保存request、response 问题，暂时先留到，目前在shiro url中设置成anon拦截器的话不会过shiro
        RequestResponseContext.setRequest(request);
        RequestResponseContext.setResponse(response);

        HttpSession session=request.getSession();
        String method=request.getMethod();
        String requestUrl = request.getRequestURI();
        if ("GET".equalsIgnoreCase(method) || requestUrl.endsWith(".html")
                /*|| requestUrl.endsWith("hca/toHcaMapMgrNoPage.html")
                || requestUrl.endsWith("hca/toHcaListMgr.html")
                || requestUrl.endsWith("external/statistics.html")
                || requestUrl.endsWith("suggestion/toGenerateRepair.html")*/) {

            String context = request.getContextPath();
            requestUrl=StringUtils.removeStart(requestUrl,context);
            if (StringUtils.isNotBlank(requestUrl)){
                requestUrl=StringUtils.replace(requestUrl,"//","/");
            }
            String rhost=request.getRemoteHost();
            String mt1=StringUtils.substringBetween(requestUrl,"/","/");
            String menuMark=urlIdMap.get(mt1);
            if (StringUtils.isNotBlank(menuMark)){
                request.setAttribute("menuMark",menuMark);
                UserSessionVO sessionVO= SessionCacheSupport.getSessionVO();
                if (sessionVO!=null){
                    Menu m= sessionVO.getMenuById(menuMark);
                    if (m!=null){
                        request.setAttribute("menuImg",m.getImgUrl());
                    }
                    Menu subM=sessionVO.getMenuByUrl(menuMark,requestUrl);
                    if (subM!=null){
                        request.setAttribute("menuActive__",subM.getParentId());
                        request.setAttribute("menuActive_subMenu__",subM.getId());
                    }
                    
                    //菜单上下级依赖关系（用于多级菜单的选中）也可以作为功能菜单的面包屑路径
                    List<Menu> menuList = new ArrayList<Menu>();
                    menuList.add(subM);
                    while (subM != null && StringUtils.isNotBlank(subM.getParentId())) {
                        subM = sessionVO.getMenuById(subM.getParentId());
                        if(subM == null){
                            break;
                        }
                        menuList.add(subM);
                    }
                    request.setAttribute("menuActiveList",menuList);
                }
            }else{
                logger.warn("此链接不在菜单权限中" + requestUrl);
            }
        }


        String mod= ServletRequestUtils.getStringParameter(request,"AjaxMode","");
        if (StringUtils.isNotBlank(mod)){
            int pageNum = ServletRequestUtils.getIntParameter(request,"jsonBean.pageNum",0);
            int pageCount = ServletRequestUtils.getIntParameter(request,"jsonBean.pageCount",0);
            if (pageNum==0 && pageCount==0){
                //因为是绑定到线程的，而线程有线程池，如果不这样，会使用到之前某次的线程，会意外导致TempPageInfo有值。
                RequestResponseContext.setTempPageInfo(null);
            }else {
                //PageHelper.startPage(pageNum,pageCount);
                Result r=new Result();
                r.setPageNum(pageNum);
                r.setPageSize(pageCount);
                RequestResponseContext.setTempPageInfo(r);
            }
        }


        //防重复提交验证
        /*SessionVO sessionVO = SessionCacheSupport.getSessionVO();
        if(sessionVO!=null){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            AvoidDuplicateSubmission annotation = method.getAnnotation(AvoidDuplicateSubmission.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.needSaveToken();
                if (needSaveSession) {
                    request.getSession(false).setAttribute("_token", sessionVO.getLoginId()+UUIDUtil.getUUID());
                }

                boolean needRemoveSession = annotation.needRemoveToken();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                        logger.warn("please don't repeat submit,[user:" + sessionVO.getLoginId() + ",url:"
                                + request.getServletPath() + "]");
                        AjaxSupport.sendFailText("提交失败","请不要重复提交");
                        return false;
                    }
                    request.getSession(false).removeAttribute("_token");
                }
            }
        }*/
        return true;


    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(false).getAttribute("_token");
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter("_token");
        if (clinetToken == null) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }

}
